package com.hanlin.backend.controller;

import com.hanlin.backend.common.error.ErrorCodeEnum;
import com.hanlin.backend.common.util.ResultCommon;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 错误收集的controller
 *
 * @author:hl.yuan
 * @date:2021-01-06
 */
@RestController
@Slf4j
public class MyErrorController implements ErrorController {

    @RequestMapping("/error/401")
    public ResultCommon error401() {
        return new ResultCommon(ErrorCodeEnum.No_TOKEN.getCode(), ErrorCodeEnum.No_TOKEN.getDesc());
    }

    @RequestMapping("/error")
    public ResultCommon error(HttpServletRequest request) {
        int statusCode = (int) request.getAttribute("javax.servlet.error.status_code");
        log.info("MyErrorController捕获到异常请求,请求code码：{}", statusCode);
        if (statusCode == 500) {
            // 系统错误
            return new ResultCommon(ErrorCodeEnum.SYS_ERROR.getCode(), ErrorCodeEnum.SYS_ERROR.getDesc());
        } else if (statusCode == 404) {
            // 404，无效链接
            return new ResultCommon(ErrorCodeEnum.NO_RESOURCE.getCode(), ErrorCodeEnum.NO_RESOURCE.getDesc());
        } else if (statusCode == 403) {
            // 403 无权限
            return new ResultCommon(ErrorCodeEnum.NO_AUTHORITY.getCode(), ErrorCodeEnum.NO_AUTHORITY.getDesc());
        }
        return new ResultCommon(ErrorCodeEnum.ILLEGAL_ARGS.getCode(), ErrorCodeEnum.ILLEGAL_ARGS.getDesc());
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }


}
